﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using BLL = KC.Business.Web.MV8;
using DAL = KC.DataAccess.MV;

public partial class Post : System.Web.UI.Page
{
	public DAL.Post p;
	public DAL.MV8DataContext dc;
	protected void Page_Load(object sender, EventArgs e)
	{
		dc = new DAL.MV8DataContext(ConfigurationManager.ConnectionStrings["MV8"].ConnectionString);
		Dictionary<string, string> values;

		KC.Business.Web.MV8.DetectRequestType(Request.RawUrl, out values);
		if (!values.ContainsKey("id") && !values.ContainsKey("title")) Response.Redirect(".");
		int id;

		if (p == null) p = null; // trick IDE into thinking I've initialized my p

		if (values.ContainsKey("id") && int.TryParse(values["id"], out id))
		{
			var posts = from p2 in dc.Posts where p2.ID == id select p2;
			if (posts.Count() == 0) Response.Redirect(".");
			p = posts.First();
		}
		else if (values.ContainsKey("title") && !string.IsNullOrEmpty(values["title"]))
		{
			string title = Server.UrlEncode(values["title"]);
			var posts = from p2 in dc.Posts where p2.FriendlyName == title select p2;
			if (posts.Count() == 0) Response.Redirect(".");
			p = posts.First();
		}
		else {
			//TODO
			//KC.Logging.Logger.Write("MV7", "User arrived at Post.aspx without a valid request", "No ID nor Title detected in URL "+Request.RawUrl, KC.Logging.Logger.Severity.Error);
			Response.Redirect("."); }

		//TODO
		PopulatePost(p, dc);

		// Detect and add canonical link
		string linkrel = string.IsNullOrEmpty(p.FriendlyName)
			? "<link rel=\"canonical\" href=\"http://www.kconnolly.net/Post.aspx?ID=" + p.ID.ToString() + "\" />"
			: "<link rel=\"canonical\" href=\"http://www.kconnolly.net/Post.aspx?Title=" + p.FriendlyName + "\" />";
		Page.Header.Controls.Add(new LiteralControl(linkrel));
	}

	private void PopulatePost(DAL.Post p, DAL.MV8DataContext dc)
	{
		lblBody.Text = KC.Business.Text.Encoding.BlogDecodeForRendering(p.Body);
		lblCreated.Text = "Posted " + p.Created.ToString();
		hlTitle.Text = p.Title;
		hlTitle.NavigateUrl = string.IsNullOrEmpty(p.FriendlyName)
			? "Post.aspx?ID=" + p.ID.ToString()
			: "Post.aspx?Title=" + p.FriendlyName;
		Title = p.Title + " - Kevin Connolly";

		lblComments.Text = site.GetFacebookCommentsScript("http://www.kconnolly.net/Post.aspx?Title=" + p.FriendlyName);
		lblFacebook.Text = site.GetFacebookLikeButton("http://www.kconnolly.net/Post.aspx?Title=" + p.FriendlyName);
		this.Page.Header.Controls.Add(new LiteralControl() { Text = "<meta property=\"og:title\" content=\"" + p.Title + "\" />\r\n" });
	}
}